const {
	readFile,
	writeFile
} = require('node:fs')
const {
	basename
} = require('node:path')
const {
	URL
} = require("node:url");

function openFile(options) {
	return new Promise((resolve, reject) => {
		const paths = utools.showOpenDialog(options)
		const path = paths[0]
		if (path) {
			readFile(path, (err, data) => {
				if (err) {
					reject(err)
					return
				}
				const blob = new Blob([data], {
					type: 'application/octet-stream'
				})
				resolve(new File([blob], basename(path)))
			})
		}
	})
}

async function downloadFile(data, name) {
	const target = utools.showSaveDialog({
		title: '请选择文件保存位置',
		buttonLabel: '保存',
		defaultPath: name
	})
	if (!target) {
		return Promise.reject()
	}
	return new Promise(async (resolve, reject) => {
		// 数据URL
		let byteCharacters = atob(
			data.replace(/^data:(.*?)base64,/, "")
		)
		let byteNumbers = new Array(byteCharacters.length)
		for (let i = 0; i < byteCharacters.length; i++) {
			byteNumbers[i] = byteCharacters.charCodeAt(i)
		}
		let byteArray = new Uint8Array(byteNumbers)
		writeFile(target, byteArray, e => {
			if (e) {
				return reject(e)
			}
			resolve(target)
		})
	})
}

window.preload = {
	openFile,
	downloadFile
}